package mware_lib;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Communication {
    private String host;
    private int port;

    public Communication(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void send(Object object) {
        try {
            if(Config.DEBUGGER) System.out.println("Communication send mit Object :" + object.getClass());
            Socket socket = new Socket(host, port);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(object);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Object sendAndReceive(Object object) {
        try {
            if(Config.DEBUGGER) System.out.println("Communication 'send'AndReceive mit Object :" + object.getClass());
            Socket socket = new Socket(host, port);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            out.writeObject(object);
            Object objectIn = in.readObject();
            if(Config.DEBUGGER) System.out.println("Communication sendAnd'Receive' mit ObjectIn :" + objectIn.getClass());
            return objectIn;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getHost() {
        return this.host;
    }

    public int getPort() {
        return this.port;
    }
}
